<?php

/**
 * This is the model class for table "tbl_invoice_equipment".
 *
 * The followings are the available columns in table 'tbl_invoice_equipment':
 * @property integer $id
 * @property string $invoice
 * @property string $counter
 * @property string $equipmentid
 * @property string $notes
 * @property string $locktime
 * @property string $lockby
 */
class InvoiceEquipment extends CActiveRecord
{
	/**
	 * Returns the static model of the specified AR class.
	 * @return InvoiceEquipment the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'tbl_invoice_equipment';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('invoice, counter, equipmentid', 'required'),
			array('invoice, equipmentid', 'length', 'max'=>15),
			array('counter', 'length', 'max'=>3),
			array('locktime', 'length', 'max'=>20),
			array('lockby', 'length', 'max'=>30),
			array('notes', 'safe'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, invoice, counter, equipmentid, notes, locktime, lockby', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'invoice' => 'Invoice',
			'counter' => 'Counter',
			'equipmentid' => 'Equipmentid',
			'notes' => 'Notes',
			'locktime' => 'Locktime',
			'lockby' => 'Lockby',
		);
	}

	public function beforeSave() {
            if($this->isNewRecord){
                $max=Yii::app()->db->createCommand('select max(cast(counter as unsigned)) from tbl_invoice_equipment where invoice=:invoice')->bindValue('invoice', $this->invoice)->queryScalar();
                if($max!==false){
                    $this->counter=str_pad($max+1, 3, '0', STR_PAD_LEFT);
                }
            }
            return parent::beforeSave();
        }
}